#encoding: utf-8
#Transfer the original training data provided by JRS organization.
#The input may contain lots of zero values. To improve the I/O time,
#we eliminate the input to be as the form:
#AttrID:Value AttrID:Value ...
#-ktchuang
import sys

if len(sys.argv) <= 2:
    print('Usage: python {0} LongInputFile EliminateOutputFile '.format(sys.argv[0]))
    raise SystemExit

print('Evaluating')
inf_ans = open(sys.argv[1])         #正確解答
inf_pred = open(sys.argv[2])        #預測解答

outf = open(sys.argv[3],'w')    #分數顯示

lines_ans = inf_ans.readlines()
lines_pred = inf_pred.readlines()

predict_right_arr = []
Accuracy = 0
test_right = 0
test_condiction = 0

avg_Fscore = 0
instance = 0                    #筆數
Precision = []
Recall = []
Fscore = []

outf.write("Prediction" + "\t|\t" + "Answer  \n")
for i in range(len(lines_ans)):
    predict_right = 0           #預測正確的
    predict_right_arr.append(0)   
    
    Precision.append(0)
    Recall.append(0)
    Fscore.append(0) 
    
    ans = lines_ans[i].split()
    pred = lines_pred[i].split()
    line_ans = lines_ans[i].split(',')
    line_pred = lines_pred[i].split(',')
    outf.write(pred[0] + "\t|\t" + ans[0] + "\t\t")
    for j in range(len(line_pred)):
        for k in range(len(line_ans)):
            if line_pred[j].split()[0] == line_ans[k].split()[0]:
                predict_right = 1
                predict_right_arr[i]+=1
                break
    if predict_right == 1:
        test_right+=1    
    outf.write(str(predict_right_arr[i]) + "/" + str(len(line_ans)) )
    
    Recall[i] = float(predict_right_arr[i])/len(line_ans)    
    Precision[i] = float(predict_right_arr[i])/len(line_pred)
    
    outf.write("\tPrecision: " + str(Precision[i]) + "\tRecall: " + str(Recall[i]) )
    if Precision[i] == 0 or Recall[i] == 0:
        Fscore[i] = 0
    else:
        Fscore[i] = 2 * Precision[i] * Recall[i] / (Precision[i] + Recall[i])
    
    outf.write("\tFscore: " + str(Fscore[i]) + '\n\n')
    
    avg_Fscore += Fscore[i]
    instance+=1    

avg_Fscore = avg_Fscore / instance             
outf.write('\n');
outf.write('avg_Fscore = ' + str(avg_Fscore) )
print('done')        
inf_ans.close();
inf_pred.close();
outf.close();